package org.itboys.manager;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.fuzion.constant.FuzionConstants;
import org.itboys.fuzion.dto.FuzionMemberDto;
import org.itboys.fuzion.dto.FuzionMemberMoneyDto;
import org.itboys.fuzion.entity.FuzionMember;
import org.itboys.fuzion.entity.ScoreLevel;
import org.itboys.fuzion.mysql.orm.FuziongMemberStatistics;
import org.itboys.fuzion.mysql.service.FuziongMemberStatisticsService;
import org.itboys.fuzion.service.FuzionMemberService;
import org.itboys.fuzion.service.ScoreLevelService;
import org.itboys.product.entity.Order;
import org.itboys.product.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户中心核心功能
 * Created by weisky on 2016/5/24.
 */
@Service
public class MemberCoreService {

    @Autowired
    private FuzionMemberService fuzionMemberService;
    @Autowired
    private FuziongMemberStatisticsService fuziongMemberStatisticsService;
    @Autowired
    private ScoreLevelService scoreLevelService;
    @Autowired
    private OrderService orderService;

    private static final Long QINGTONG_SCORE_ID = 1L;
    private static final Long BAIJIN_SCORE_ID = 2L;
    private static final Long WANGZHE_SCORE_ID = 3L;
    private static final Long ZHANSHEN_SCORE_ID = 4L;
    private static final Long TIANGANG_SCORE_ID = 5L;
    private static final Long JIAOFU_SCORE_ID = 6L;

    /**
     * 组装在微信的会员中心看到的信息
     * @param memberId
     * @return
     */
    public FuzionMemberDto getByMemberId(Long memberId){
        FuziongMemberStatistics fms = fuziongMemberStatisticsService.getByMember(memberId);

        FuzionMemberDto fmd = new FuzionMemberDto();
        fmd.setScoreId(fms.getScoreId());
        if(fms != null){
            List<Long> buyMemberListId = getTodayOrderMemberId();//今日购买过的会员ID

            /**
             * 青铜收益
             */
            FuzionMemberMoneyDto qt = income(QINGTONG_SCORE_ID, fms.getSellerId(), FuzionConstants.Money.BRONZE_MONEY, buyMemberListId);

            /**
             * 白金收益
             */
            FuzionMemberMoneyDto bj = income(BAIJIN_SCORE_ID, fms.getSellerId(), FuzionConstants.Money.PLATINA_MONEY, buyMemberListId);

            /**
             * 王者收益
             */
            FuzionMemberMoneyDto wz = income(WANGZHE_SCORE_ID, fms.getSellerId(), FuzionConstants.Money.KING_MONGEY, buyMemberListId);

            /**
             * 战神收益
             */
            FuzionMemberMoneyDto zs = income(ZHANSHEN_SCORE_ID, fms.getSellerId(), FuzionConstants.Money.ZHANSHEN_MONGEY, buyMemberListId);

            /**
             * 天罡收益
             */
            FuzionMemberMoneyDto tg = income(TIANGANG_SCORE_ID, fms.getSellerId(), FuzionConstants.Money.TIANGANG_MONGEY, buyMemberListId);
            /**
             * 教父收益
             */
            FuzionMemberMoneyDto jf = income(JIAOFU_SCORE_ID, fms.getSellerId(), FuzionConstants.Money.JIAOFU_MONGEY, buyMemberListId);

            List<FuzionMemberMoneyDto> incomeList = Lists.newArrayListWithExpectedSize(3);
            incomeList.add(wz);
            incomeList.add(bj);
            incomeList.add(qt);
            incomeList.add(zs);
            incomeList.add(tg);
            incomeList.add(jf);
            fmd.setMoneyDto(incomeList);

            //if(fms.getScoreId() != 0){//有会员等级的  才能参与计算
            fmd.setEnergyBean(fms.getNowEnergyBean());//现在拥有的能量豆数量
            fmd.setHistoryAllMoney(new BigDecimal(fms.getTotalMoney()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP));//历史总收益 要除以100  单位变成元
            fmd.setScore(new BigDecimal(fms.getNowTotalMoney()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP));//当前积分  其实就是钱(剩余可提现的总金额  以分为单位  除以100  就是以元为单位)
            fmd.setDynamicIncome(new BigDecimal(fms.getDynamicIncome()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP));//动态收益  直推收益
            fmd.setStaticIncome(new BigDecimal(fms.getStaticIncome()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP));//静态收益  每日分红（青铜收益）和开奖
            fmd.setPlayNum(fms.getPlayNum());
            //}
        }
        return fmd;
    }

    /**
     * 计算等级的各种收益
     * @param scoreId : 积分等级ID
     * @param sellerId : 店铺ID
     * @param type : 积分等级类型  1：青铜  2：白金  3：王者
     * @return
     */
    public FuzionMemberMoneyDto income(Long scoreId, Long sellerId, int type, List<Long> buyMemberListId){
        ScoreLevel sl = scoreLevelService.getById(scoreId);
        List<Long> qtMemberIdList = fuziongMemberStatisticsService.getMemberIdListByScoreId(scoreId, sellerId);//这里的ID写死了
        int qtMemberNum = qtMemberIdList.size();

        Integer dawdlerNum = 0;//懒人数量
        Integer hardworkingNum = fuziongMemberStatisticsService.getMemberBuyType(scoreId, sellerId);//勤快人的数量

        //这里后台控制每日分红人数
        if(sl.getPeopleNum() != null && sl.getPeopleNum() >= 0){
            qtMemberNum = sl.getPeopleNum();
        }

        //计算懒人数量
        if(qtMemberNum > hardworkingNum){
            dawdlerNum = qtMemberNum - hardworkingNum;
        }

		/*if(!qtMemberIdList.isEmpty()){
			qtMemberNum = publicRowService.getNumByMemberId(qtMemberIdList);//奖金池中的青铜人数
		}*/
        FuziongMemberStatistics sellerInco = fuziongMemberStatisticsService.getSellerIncome(sellerId);//店铺收益

        FuzionMemberMoneyDto fmmd = new FuzionMemberMoneyDto();
        BigDecimal total = new BigDecimal(sellerInco.getNowTotalMoney()).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);//总销售额

        BigDecimal poolMoney = total.multiply(new BigDecimal(sl.getPercent())).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);//奖金池 总的销售额*5%
        BigDecimal dawdler = poolMoney.multiply(new BigDecimal(sl.getDawdler())).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);//懒人金额
        BigDecimal hardworking = poolMoney.multiply(new BigDecimal(sl.getHardworking())).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);//勤快人的金额

        fmmd.setPoolMoney(poolMoney);//奖金池的金额
        fmmd.setMoney(fmmd.getPoolMoney());//青铜等级收益=奖金池
        fmmd.setNum(qtMemberNum);//参与人数
        if(qtMemberNum > 0){
            fmmd.setCanMoney(fmmd.getPoolMoney().divide(new BigDecimal(qtMemberNum),2, BigDecimal.ROUND_HALF_UP));//可获收益 奖金池/青铜人数
        }
        if(dawdlerNum > 0){
            fmmd.setDawdler(dawdler.divide(new BigDecimal(dawdlerNum),2, BigDecimal.ROUND_HALF_UP));//懒人可获收益
        }
        if(hardworkingNum > 0){
            fmmd.setHardworking(hardworking.divide(new BigDecimal(hardworkingNum),2, BigDecimal.ROUND_HALF_UP));//勤快人收益
        }else{//如果勤人为0  就拿奖金池中的金额减去懒人的金额
            fmmd.setHardworking(poolMoney.subtract(fmmd.getDawdler()));//勤快人收益
        }

        fmmd.setType(type);//青铜级别
        return fmmd;
    }

    /**
     * 判断会员今天是否是懒人
     * @param memberId
     * @return true：懒人   false:勤快人
     */
    public boolean isDawdler(Long memberId, List<Long> buyMemberListId){
        List<Long> myTeamMemberId = getMyBuyMemberId(memberId);//我的直推会员Id
        //List<Long> buyMemberListId = getTodayOrderMemberId();//今日购买过的会员ID
        boolean mark = true;
        for (int i = 0; i < myTeamMemberId.size(); i ++){
            if(buyMemberListId.contains(myTeamMemberId.get(i))){//如果这个会员在今日买过东西  进入
                mark = false;
                break;//只要有一个人已经买过  就跳出循环
            }
        }
        return mark;
    }

    /**
     * 获取我的团队中已经购买过的会员ID
     * @param memberId
     * @return
     */
    public List<Long> getMyBuyMemberId(Long memberId){
        List<FuzionMember> list = fuzionMemberService.getMyBuyMember(memberId);
        if(list != null && list.size() > 0){
            List<Long> mList = Lists.newArrayListWithExpectedSize(list.size());
            list.forEach(l ->{
                mList.add(l.getId());
            });
            return mList;
        }
        return null;
    }

    /**
     * 获取当日成功交易的会员ID列表
     * @return
     */
    public List<Long> getTodayOrderMemberId(){
        List<Order> orderList = getTodayOrder();
        if(orderList != null && orderList.size() > 0){
            List<Long> list = Lists.newArrayListWithExpectedSize(orderList.size());
            orderList.forEach(o -> {
                list.add(o.getMemberId());
            });
            return list;
        }
        return null;
    }

    /**
     * 获取今天成功交易的订单列表
     * @return
     */
    private List<Order> getTodayOrder(){

        String s = TimeUtils.format(new Date(), "yyyy-MM-dd") + " 00:00:01";
        String e = TimeUtils.format(new Date(), "yyyy-MM-dd") + " 23:59:59";
        Map<String, Object> param = Maps.newHashMapWithExpectedSize(4);
        param.put("productId",0);
        param.put("status",1);
        param.put("ut >= ", TimeUtils.getDateValue(s).getTime());
        param.put("ut <= ",TimeUtils.getDateValue(e).getTime());

        List<Order> orderList = orderService.list(param);
        return orderList;
    }

}
